#!/bin/bash

# 前端修复自动化脚本
# 用法: ./scripts/apply-fixes.sh [--dry-run]

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
ARTIFACTS_DIR="$PROJECT_ROOT/artifacts"
PATCHES_DIR="$ARTIFACTS_DIR/patches"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查是否为dry-run模式
DRY_RUN=false
if [[ "$1" == "--dry-run" ]]; then
    DRY_RUN=true
    log_info "运行在dry-run模式，不会实际修改文件"
fi

# 检查必要文件
check_prerequisites() {
    log_info "检查前置条件..."
    
    if [[ ! -d "$ARTIFACTS_DIR" ]]; then
        log_error "artifacts目录不存在，请先运行: npm run diag"
        exit 1
    fi
    
    if [[ ! -d "$PATCHES_DIR" ]]; then
        log_error "补丁目录不存在: $PATCHES_DIR"
        exit 1
    fi
    
    # 检查git状态
    if ! git diff --quiet; then
        log_warning "工作目录有未提交的更改，建议先提交或暂存"
        if [[ "$DRY_RUN" == "false" ]]; then
            read -p "是否继续? (y/N): " -n 1 -r
            echo
            if [[ ! $REPLY =~ ^[Yy]$ ]]; then
                exit 1
            fi
        fi
    fi
    
    log_success "前置条件检查通过"
}

# 备份当前状态
create_backup() {
    if [[ "$DRY_RUN" == "true" ]]; then
        log_info "[DRY-RUN] 将创建备份..."
        return
    fi
    
    log_info "创建备份..."
    BACKUP_DIR="$PROJECT_ROOT/backup-$(date +%Y%m%d-%H%M%S)"
    mkdir -p "$BACKUP_DIR"
    
    # 备份src目录
    cp -r "$PROJECT_ROOT/src" "$BACKUP_DIR/"
    
    log_success "备份已创建: $BACKUP_DIR"
}

# 应用错误处理包装器
apply_error_wrapper() {
    log_info "应用统一错误处理包装器..."
    
    local source_file="$PATCHES_DIR/error-handling-wrapper.js"
    local target_dir="$PROJECT_ROOT/src/utils"
    local target_file="$target_dir/error-handling-wrapper.js"
    
    if [[ ! -f "$source_file" ]]; then
        log_error "错误处理包装器文件不存在: $source_file"
        return 1
    fi
    
    if [[ "$DRY_RUN" == "true" ]]; then
        log_info "[DRY-RUN] 将复制 $source_file 到 $target_file"
        return
    fi
    
    mkdir -p "$target_dir"
    cp "$source_file" "$target_file"
    
    log_success "错误处理包装器已应用"
}

# 应用补丁文件
apply_patch() {
    local patch_file="$1"
    local patch_name="$(basename "$patch_file" .patch)"
    
    log_info "应用补丁: $patch_name"
    
    if [[ ! -f "$patch_file" ]]; then
        log_error "补丁文件不存在: $patch_file"
        return 1
    fi
    
    if [[ "$DRY_RUN" == "true" ]]; then
        log_info "[DRY-RUN] 将应用补丁: $patch_file"
        # 检查补丁是否可以应用
        if git apply --check "$patch_file" 2>/dev/null; then
            log_success "[DRY-RUN] 补丁 $patch_name 可以成功应用"
        else
            log_warning "[DRY-RUN] 补丁 $patch_name 可能无法应用"
        fi
        return
    fi
    
    # 尝试应用补丁
    if git apply "$patch_file"; then
        log_success "补丁 $patch_name 应用成功"
    else
        log_error "补丁 $patch_name 应用失败"
        return 1
    fi
}

# 验证修复效果
verify_fixes() {
    log_info "验证修复效果..."
    
    if [[ "$DRY_RUN" == "true" ]]; then
        log_info "[DRY-RUN] 将运行验证测试"
        return
    fi
    
    # 检查语法错误
    if npm run lint 2>/dev/null; then
        log_success "代码规范检查通过"
    else
        log_warning "代码规范检查有警告，请检查"
    fi
    
    # 尝试构建
    if npm run build 2>/dev/null; then
        log_success "构建测试通过"
    else
        log_error "构建失败，请检查错误信息"
        return 1
    fi
    
    log_success "修复验证完成"
}

# 主函数
main() {
    log_info "开始应用前端修复..."
    
    # 切换到项目根目录
    cd "$PROJECT_ROOT"
    
    # 执行修复步骤
    check_prerequisites
    create_backup
    apply_error_wrapper
    
    # 应用所有补丁
    local patches=(
        "reports-error-handling.patch"
        "coupons-layout-fix.patch"
        "menu-error-handling.patch"
    )
    
    for patch in "${patches[@]}"; do
        apply_patch "$PATCHES_DIR/$patch"
    done
    
    verify_fixes
    
    if [[ "$DRY_RUN" == "true" ]]; then
        log_info "Dry-run完成，没有实际修改文件"
        log_info "如需应用修复，请运行: ./scripts/apply-fixes.sh"
    else
        log_success "所有修复已应用完成！"
        log_info "请运行以下命令验证:"
        log_info "  npm run dev    # 启动开发服务器"
        log_info "  npm run diag   # 运行诊断检查"
    fi
}

# 错误处理
trap 'log_error "脚本执行失败，请检查错误信息"' ERR

# 执行主函数
main "$@"